package router

import (
	"xServer/config"
	"xServer/internal/controller/file"
	"xServer/internal/controller/user"
	"xServer/internal/middleware"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func RegisterRoutes(router *gin.Engine, cfg *config.Config) *gin.Engine {
	//router := gin.Default()

	// 配置静态文件服务
	router.Static("/static", "./static")

	// 配置CORS
	router.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"http://localhost:3000", "http://127.0.0.1:3000"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// 页面路由
	router.GET("/login", func(c *gin.Context) {
		c.File("static/html/login.html")
	})
	router.GET("/register", func(c *gin.Context) {
		c.File("static/html/register.html")
	})
	router.GET("/files", func(c *gin.Context) {
		c.File("static/html/files.html")
	})

	// API路由
	api := router.Group("/api")
	{
		// 无需认证的路由
		public := api.Group("/")
		{
			userRoutes := public.Group("/user")
			{
				userRoutes.POST("/login", user.Login)
				userRoutes.POST("/register", user.Register)
			}
		}

		// 需要认证的路由
		auth := api.Group("/")
		auth.Use(middleware.AuthMiddleware(cfg.Secret))
		{
			// 用户相关路由
			userRoutes := auth.Group("/user")
			{
				userRoutes.GET("/current", user.GetCurrentUser)
				userRoutes.PUT("/password", user.ChangePassword)
			}

			// 文件相关路由
			fileRoutes := auth.Group("/files")
			{
				fileRoutes.POST("/directory", file.CreateDirectory)
				fileRoutes.GET("/directory", file.ListDirectories)
				fileRoutes.GET("/directory/:id", file.GetDirectory)
				fileRoutes.PUT("/directory/:id", file.UpdateDirectory)
				fileRoutes.DELETE("/directory/:id", file.DeleteDirectory)
				//fileRoutes.GET("/directory/:directory_id/files", file.ListFilesInDirectory)
				fileRoutes.POST("/upload", file.UploadFile)
				fileRoutes.GET("/:id", file.GetFile)
				fileRoutes.PUT("/:id", file.UpdateFile)
				fileRoutes.DELETE("/:id", file.DeleteFile)
				fileRoutes.GET("/download/:id", file.DownloadFile)
				fileRoutes.POST("/:id/access-token", file.GenerateAccessToken)
			}
			directoriesRoutes := auth.Group("/directories")
			{
				// 目录相关路由
				//router.GET("/api/directories", file.ListDirectory)
				directoriesRoutes.GET("/detail", file.DirectoryDetail)
				directoriesRoutes.POST("/create", file.CreateDirectory)
				directoriesRoutes.PUT("/:id", file.UpdateDirectory)
				directoriesRoutes.DELETE("/:id", file.DeleteDirectory)
			}
		}
	}

	// 公开文件下载路由
	router.GET("/public/download", file.DownloadPublicFile)

	return router
}
